/**
 * Created with IntelliJ IDEA.
 * User: inester
 * Date: 29.06.12
 * Time: 13:45
 */

//async load data for selected node into information panel
var showInfo = function(node){
    var infoPanel = Ext.getCmp('infoPanelId');
    infoPanel.el.mask('Please wait','x-mask-loading');
    Ext.Ajax.request({
        url    : 'data/getElement',
        params : {
            nodeId: node.id
        },
        success: function(response, opts) {
            infoPanel.el.unmask();

            var responseJson = Ext.decode(response.responseText);
            if (responseJson.success === "true") {

                //specific for different kind of node form panel items
                var formPanelItems;

                //check type of selected tree node
                var isEmployee = node.id.match("Employee_");
                var isRoot = (node.id == organizationName);

                if (isEmployee){
                    formPanelItems = createEmployeeFormPanel(responseJson);
                }
                else{
                    formPanelItems = createCommonFormPanel(responseJson,node.id);
                }

                //create buttons if selected node is not root node of treepanel
                var formButtons;
                if (!isRoot){
                    formButtons = [
                        {
                            xtype:'button',
                            text:'Save',
                            handler:saveBtnHandler
                        },
                        {
                            xtype:'button',
                            text:'Cancel',
                            handler:cancelFormBtnHandler
                        }
                    ]
                }

                //create form panel
                var infoForm = new Ext.form.FormPanel({
                    id          : 'formInfoPanelId',
                    name        : 'formInfoPanelId',
                    items		: formPanelItems,
                    buttons     : formButtons,
                    buttonAlign : 'left',
                    defaults    : {
                        msgTarget: 'side'
                    }
                });

                //add hidden fields to form
                var nodeId = new Ext.form.Hidden ({
                    id:'nodeId',
                    name:'nodeId',
                    value:node.id
                });
                infoForm.add(nodeId);

                //assign content of form panel to east region container of application
                infoPanel.removeAll();
                infoPanel.add(infoForm);
                infoPanel.doLayout();
            }
            else{
                alert("can't fetch data for selected node");
            }
        },
        failure: function(response, opts){
            infoPanel.el.unmask();
            alert('server-side failure with status code ' + response.status);
        }
    });
};

function parseValidateOptions(vOpts){
    if (!vOpts || vOpts == undefined)
        vOpts = {};
    if (vOpts.allowBlank==undefined)
        vOpts.allowBlank = true;
    if (vOpts.vtype==undefined)
        vOpts.vtype = null;
    return vOpts;
}

function createTextField(fieldId,fieldLabel,fieldValue,vOpts,editable){
    if (editable == undefined)
        editable=true;
    var vOptsArr = parseValidateOptions(vOpts);
    return new Ext.form.TextField({
        name: fieldId,
        fieldLabel: fieldLabel,
        value: fieldValue,
        editable: editable,
        readOnly: !editable,
        width:400,
        labelStyle: 'font-weight:bold;width:150;',
        msgTarget:'side',
        allowBlank:vOptsArr.allowBlank,
        vtype:vOptsArr.vtype
    });
}

function convertDateToDateFieldValue(date){
    if (date == undefined)
        return null
    return date?new Date(date):null
}

function createDateField(fieldId,fieldLabel,fieldValue){
    return new Ext.form.DateField({
        name: fieldId,
        format: "Y-m-d",
        fieldLabel: fieldLabel,
        value: convertDateToDateFieldValue(fieldValue),
        labelStyle: 'font-weight:bold;width:150;',
        width:100,
        msgTarget:'side'
    });
}

function createTextArea(fieldId,fieldLabel,fieldValue){
    return new Ext.form.TextArea({
        name: fieldId,
        fieldLabel: fieldLabel,
        value: fieldValue,
        labelStyle: 'font-weight:bold;width:150;',
        height: 100,
        width: 400,
        msgTarget:'side'
    });
}

var updateSuccessOrFail = function(form,action){
    var mainViewport = Ext.getCmp('mainViewportId');
    mainViewport.el.unmask();
    var treePanel = Ext.getCmp('treepanel');
    var result = action.result;
    if (result.success==="true"){
        //change text into updated node
        var treePanel =  Ext.getCmp('treepanel');
        var selNode = treePanel.getNodeById(result.nodeId);
        selNode.ensureVisible(function(){
            selNode.select();
            selNode.setText(result.newName);
            showInfo(selNode);
        });
    }
    else{
        Ext.Msg.alert("Error","Update failed. Check all fields to valid values.");
    }
}

var saveBtnHandler = function(){
    var mainViewport = Ext.getCmp('mainViewportId');
    mainViewport.el.mask('Please wait...', 'x-mask-loading');
    var formPanel = Ext.getCmp('formInfoPanelId');
    formPanel.getForm().submit({
        url : "data/update",
        success: updateSuccessOrFail,
        failure: updateSuccessOrFail
    });
}

var cancelFormBtnHandler = function(){
    var formPanel = Ext.getCmp('formInfoPanelId');
    formPanel.getForm().reset();
}

//create form panel items for root, departments and projects nodes
function createCommonFormPanel(response,nodeId){
    var fpItems;

    var isRoot = (nodeId == organizationName);

    //set labels for text fields
    var fieldSetTitle;
    var fieldNameLabel = "Name";
    var fieldDateCreatedLabel = "Date created";
    var fieldDateStartLabel = "Start date";
    var fieldDateDueLabel = "Due date";
    var fieldDescriptionLabel = "Description";
    if (isRoot)
    {
        fieldNameLabel = "Organization name";
        fieldSetTitle = "Organization info";
    }
    else if(nodeId.match("Department_")){
        fieldNameLabel = "Department name";
        fieldSetTitle = "Department info";
    }
    else if(nodeId.match("Project_")){
        fieldNameLabel = "Project name";
        fieldSetTitle = "Project info";
    }

    // fill formPanel
    if (isRoot){
        var infoTitle = createTextField('name',fieldNameLabel,response.name,{},false);
        fpItems = [infoTitle];
    }
    else if(nodeId.match("Department_")){
        var infoTitle = createTextField('name',fieldNameLabel,response.name,{allowBlank:false});
        var infoDateCreated = createDateField('dateCreated',fieldDateCreatedLabel,response.dateCreated);
        var infoDescription = createTextArea('description',fieldDescriptionLabel,response.description);
        fpItems = [infoTitle,infoDateCreated,infoDescription];
    }
    else if (nodeId.match("Project_")){
        var infoTitle = createTextField('name',fieldNameLabel,response.name);
        var infoDateStart = createDateField('startDate',fieldDateStartLabel,response.startDate);
        var infoDateDue = createDateField('dueDate',fieldDateDueLabel,response.dueDate);
        var infoDescription = createTextArea('description',fieldDescriptionLabel,response.description);
        fpItems = [infoTitle,infoDateStart,infoDateDue,infoDescription];
    }
    return {
        xtype: 'fieldset',
        title: fieldSetTitle,
        items: fpItems
    };
}

//create form panel items with tabs for employee information page
function createEmployeeFormPanel(response){
    var fpItems;

    var commonFieldSet = {
        xtype: 'fieldset',
        title: 'Common employee info',
        defaultType: 'field',
        items: [
            createTextField('lastName','Last name',response.lastName,{allowBlank:false}),
            createTextField('firstName','First name',response.firstName,{allowBlank:false})
        ]
    };

    var gendersStore = new Ext.data.ArrayStore ({
        data:[['M','Male'],['F','Female']],
        fields:['genderValue','genderString']
    });
    var tabs = [
        {
            xtype:'panel',
            title:'Summary',
            layout:'form',
            frame:true,
            items: [
                createTextField('workPosition','Position',response.workPosition),
                createDateField('hireDate','Hire date',response.hireDate)
            ]
        },
        {
            xtype:'panel',
            title:'Contacts',
            layout:'form',
            frame:true,
            items: [
                createTextField('extensionPhone','Extention phone',response.extensionPhone),
                createTextField('mobilePhone','Mobile phone',response.mobilePhone),
                createTextField('homePhone','Home phone',response.homePhone),
                createTextField('email','E-mail',response.email,{vtype:'email'})
            ]
        },
        {
            xtype:'panel',
            layout:'form',
            frame:true,
            title:'Address',
            items: [
                createTextField('addressStreetCity','Street, City',response.addressStreetCity),
                createTextField('addressHouse','House',response.addressHouse),
                createTextField('addressApartment','Apartment',response.addressApartment)
            ]
        },
        {
            xtype:'panel',
            layout:'form',
            frame:true,
            title:'Passport data',
            items: [
                createDateField('birthDate','Birth date',response.birthDate),
                {
                    xtype:'combo',
                    fieldLabel: 'Gender',
                    name: 'gender_visible',
                    hiddenName: 'gender',
                    value: response.gender,
                    labelStyle: 'font-weight:bold;width:150;',
                    store: gendersStore,
                    displayField: 'genderString',
                    valueField: 'genderValue',
                    mode: 'local',
                    width: 100,
                    editable: false,
                    typeAhead: true,
                    triggerAction:'all',
                    msgTarget: 'side',
                    selectOnFocus:true
                }
            ]
        }
    ];
    var tabPanel = {
        xtype:'tabpanel',
        activeTab:0,
        layoutOnCardChange:true,
        border:false,
        height:160,
        items:tabs
    };

    fpItems = [
        commonFieldSet,
        tabPanel
    ];
    return fpItems;
}
